/***********************到货新版js**************************************/
/*点击运单号显示弹层并可查询运单信息*/
var trackeCodeName =[
    {code: "STO", name: "申通"}
    , {code: "TTKD", name: "天天"}
    , {code: "DBL", name: "德邦"}
    , {code: "ZTO", name: "中通"}
    , {code: "YD", name: "韵达"}
    , {code: "YTO", name: "圆通"}
    , {code: "DBKD", name: "德邦快递"}
    , {code: "ZTOKY", name: "中通快运"}
    , {code: "SF", name: "顺丰"}
    , {code: "EMS", name: "EMS"}
    , {code: "HTKY", name: "百世快递"}
    , {code: "BTWL", name: "百世快运"}
    , {code: "FAST", name: "快捷速递"}
    , {code: "QFKD", name: "全峰快递"}
    , {code: "UC", name: "优速"}
    , {code: "GTO", name: "国通快递"}
    , {code: "YZBK", name: "邮政国内标快"}
    , {code:"JT",name:"极兔"}
    , {code:"YMDD",name:"壹米滴答"}
    , {code:"SXJD",name:"顺心捷达"}
    , {code:"ANWL",name:"安能物流"}
    , {code:"STKD",name:"速腾快递"}
    , {code:"XFWL",name:"信丰物流"}
    , {code: "OTHER", name: "其他"}
];
var requestUrl = gitWinLocHref();
//点击物流追踪号获取物流追踪信息
var getLogisticsMsg = function  (purchasingId,trackingNumber,purchasingTrackUrl) {
    var logisticsModalData = $('#logisticsModal').find("table[id='logisticsTable']");
    logisticsModalData.empty();
    if (purchasingId && trackingNumber) {
        $.post('dxmPurchasingNote/getLogisticsMsg.json', {purchasingId: purchasingId,trackingNumber:trackingNumber}, function (data) {
            if (data) {
                for (var key in data) {
                    logisticsModalData.append("<tr><td valign='top' width='25%' style='color: coral'>"+key+"</td><td width='75%'>"+data[key]+"</td></tr><tr style='height: 10px'></tr>");
                }
                $("#logisticsModal table tr:first td:last").css("font-weight","bold");
                $('#logisticsModal').modal('show');
            } else {
                window.open(purchasingTrackUrl + trackingNumber);
            }
        });
    }
};
var purchasing = (function ($, D, W) {
    $(document).off('click','div.keyToStart');
    $(document).on('click','div.keyToStart',function(){
        var open = $(this).closest('table').find('tbody td a.productShowAllHtml'),
            $detail = $("tr[id*='detail_']"),
            isFinancePay = $(this).hasClass('financePay') ? 1 : 0,
            isPurchaslAndApplyMoney = false; // 是否为采购付款页

        if ($(this).closest('#purchaslAndApplyMoney')) isPurchaslAndApplyMoney = true;


        if($(this).attr('datatype') == '1'){
            var $purchaseTr = $('.purchaseTr'), arr = [],
                purchasePayment = $('#PurchasePaymentId').val(); //采购付款-待付款

            if (purchasePayment === 'purchasePayment') { //兼容采购付款-待付款展开详情
                $.each($purchaseTr, function (i, j) {
                    if ($(j).attr('noteid')) arr.push($(j).attr('noteid'));
                });
            } else {
                $.each($purchaseTr, function (i, j) {
                    if ($(j).attr('id')) arr.push($(j).attr('id'));
                });
            }

            $.each($detail,function (i,j) {
                if(!$(j).find('.details-list').length){
                    $('#loading').modal('show');
                    $.ajax({
                        url: requestUrl + 'dxmPurchasingNote/commDetail.json',
                        data:{
                            ids: arr.join(),
                            isFinancePay: isFinancePay
                        },
                        success:function (data) {
                            $('#loading').modal('hide');
                            purchasing.commPurDetail(data, 'all');
                            $('[data-toggle="popover"]').popover();
                            var leftState = $('#state').val();
                            if (leftState === 'canApply') {  //采购付款模块图片放大
                                $('div.imgDivIn').picZoom({
                                    imgWidth: '296',
                                    imgHeight: '296',
                                    divWidth: '300',
                                    divHeight: '300'
                                });
                            } else {
                                initFindGoods('imgDivIn', 'pageState');//注册找货源
                            }
                            purchasing.lightShowSkuDetail(null, $('#alibabaSearchType').length);//高亮显示搜索的sku所对应的那个产品信息
                        }
                    });
                    return false;
                }
            });
            open.attr('data-type','1');
            $detail.removeClass(isPurchaslAndApplyMoney ? 'hide' : 'myj-hide');
            $(this).attr('datatype',0).html('(- 收起)');
        }else{
            open.attr('data-type','0');
            $detail.addClass(isPurchaslAndApplyMoney ? 'hide' : 'myj-hide');
            $(this).attr('datatype',1).html('(+ 展开)');
        }
    });


    var isCommitOver = false;
    return {
        arrivalGoods: function (that, po) {
            var id = $(that).closest('tr').attr('id');
            if (isCommitOver) {
                return;
            }
            isCommitOver = true;

            //验证单子是否应该在签收管理中去进行到货操作
            var status = purchasing.getPutInStatus();
            if (+status !== 0) {
                $.fn.message({type: 'error', msg: '采购流程处于“' + (+status === 1 ? '标准模式' : (+status === 2 ? '签收质检+入库' : '签收+质检入库')) + '”模式，请到收货管理中去处理到货'});
                isCommitOver = false;
                reloadPro();
                return;
            }

            $.post('dxmPurchasingNote/checkCanActionForChange.json', {ids: id}, function(data){
                $('#loading').modal('hide');
                if (!+data.code) {
                    purchasing.arrivalGoodsModal(id);
                    return;
                }
                isCommitOver = false;
                var msg = data.msg;

                if (msg === '采购单变更中，不能进行相关操作，请先处理采购变更单'
                    || msg === '请先处理已驳回的采购变更单'
                    || msg.indexOf('在变更流程中') !== -1) {
                    po = po || '';
                    msg += '，<a href="' + gitWinLocHref() + 'dxmPurchasingChange/index.htm?purchasingOrder=' +
                        po + '" target="_blank">去处理</a>';
                }
                $.fn.message({type: 'error', msg: msg});
            });
        },

        //获取到货流程是否开启
        getPutInStatus: function () {
            var status = 1;
            $.ajax({
                type: 'get',
                url: 'userConfig/getPutInStatus.json',
                data: {},
                async: false,
                success: function (data) {
                    if (data == -1) {
                        $.fn.message({type: 'error', msg: '获取配置失败'});
                        return;
                    }
                    status = data;
                }
            });
            return status;
        },
        //先设置排序字段为空
        arrivalGoodsModal: function (id) {
            $("#sortType").val("");
            var $tr = $('tr'),
                spanObj = $tr.find("span[name='Caret']");
            $(spanObj).removeClass("myjCaretDown").removeClass("myjCaretUp");
            $tr.find("span[ps='up']").addClass("myjCaretUp");        //向上向下的排序
            $tr.find("span[ps='down']").addClass("myjCaretDown");   //向上向下的排序
            $('#loading').modal('show');
            if (id) {
                $.ajax({
                    type: 'get',
                    url: 'dxmPurchasingNote/getArrivalProduct.htm',
                    data: {
                        id: id
                    },
                    dataType: 'html',
                    success: function (data) {
                        $('div[uid="arrivalProduct"]').html(data);
                        $('#loading').modal('hide');
                        $('#purchasingNoAll').text($('#hiddenPurchasingInfo').attr('data-purchasingnoall'));
                        $('#CreateShoppingListA').modal('show');
                        $('#isPrintThisTime').prop('checked', false);
                        isCommitOver = false;
                        $("div.listImgIn").picZoom({
                            imgWidth: "296",
                            imgHeight: "296",
                            divWidth: "300",
                            divHeight: "300"
                        });
                    }
                });
            } else {
                $.fn.message({type: "error", msg: "到货添加失败！"});
                isCommitOver = false;
            }
        },

        //到货--选择货架位--打开货架位选择大弹窗
        openChooseGoodsShelfModal: function (that, type) {
            var warehouseId = type == "batch" ? $(that).closest('tr').attr('data-warehouseId') : $('#hiddenPurchasingInfo').attr('data-warehouseId'),
                oldGoodShelfId = $(that).closest('tr').find('span[name="changProductGoodsShelf"]').attr('data-oldId'),
                productId = $(that).closest('tr').attr('productId'),
                $chooseGoodsShelfModal = $('#chooseGoodsShelfModal'),
                url = "dxmPurchasingNote/getGoodsShelfList.htm";
            $('#loading').modal('show');
            $.ajax({
                type: 'post',
                url: url,
                data: {
                    warehouseId: warehouseId,
                    oldGoodShelfId: oldGoodShelfId
                },
                dataType: 'html',
                success: function (data) {
                    $('#loading').modal('hide');
                    $chooseGoodsShelfModal.customModal('show');
                    $chooseGoodsShelfModal.find('#chooseGoodsShelfContent').html(data);
                    $chooseGoodsShelfModal.find('#chooseWarehouseId').val(warehouseId);
                    $('#chooseWarehouseId').val(warehouseId);
                    $('#oldGoodShelfId').val(oldGoodShelfId);
                    $('#dwpId').val(productId);
                },
                error: function (e) {
                    $('#loading').modal('hide');
                }
            });
        },
        //采购单中采购的商品id
        changeNum: function (obj) {
            var $obj = $(obj);
            clearMistakeNumber($obj);
            var num = $obj.val(),
                historyNum = $obj.closest('tr').find('#hiddenInfo').attr('data-alreadynum');

            if (!num) {
                num = 0;
            }
            var arrivalNum = $obj.closest('tr').find('td:eq(2)').find('span');
            arrivalNum.html(0);
            arrivalNum.html(parseInt(historyNum, 10) + parseInt(num));
        },

        batchPlDh: function (type) {
            if(type === 1){
                var $tr = $('#inWarehouseTbody > tr'),
                    arrivalSum = 0,
                    priceSum = 0;
                $.each($tr, function(i, j){
                    var $leftArriveCount = $(j).find('.leftArriveCount'),
                        value = +$leftArriveCount.text();

                    $(j).find('.arrivalCount').val(value);
                });
            }else{
                $.each($("input[uid^='num_']"), function () {
                    var alreadNum = $(this).closest('tr').find('#hiddenInfo').attr('data-alreadynum'),
                        allNum = $(this).closest('tr').find('#hiddenInfo').attr('data-allnum');
                    $(this).val(allNum - alreadNum);
                    $(this).closest('tr').find('td:eq(2)').find('span').html(allNum);
                });
            }
        },

        batchQkDh: function (type) {
            if(type === 1){
                var $tr = $('#inWarehouseTbody > tr');

                $tr.find('.arrivalCount').val('');
            } else{
                $.each($("input[uid^='num_']"), function () {
                    var alreadyNum = $(this).closest('tr').find('#hiddenInfo').attr('data-alreadynum');
                    $(this).val('');
                    $(this).closest('tr').find('td:eq(2)').find('span').html(alreadyNum);
                });
            }
        },

        fillPrintData: function(that) {
            var inputVal = $.trim($(that).closest('div').find('input').val());
            $(that).closest('div').addClass('myj-hide');
            $(that).closest('.modal-content').find('.clickShowPrintNumModal').attr('data-type', 0);
            $('#batchPurchasingSkuLabel').find('tr').each(function () {
                $(this).children('td.printQuantity').find('input').val(inputVal);
            });
        },

        saveArrival: function () {
            var $purchasingInfo = $('#hiddenPurchasingInfo'),
                purchasingId = $purchasingInfo.attr('data-id'),  //采购单id
                tempComment = $.trim($('textarea[uid="comment"]').val()),   //到货备注
                podh = $purchasingInfo.attr('data-purchasingnoall'),   //采购单号
                obj = {},
                productInfoList = [],
                productInfoObj = {},
                comment;
            if (tempComment) {
                comment = tempComment.replace(/(\n|\r\n)/g, '<br/>');
                if (comment.length > 2000) {
                    $.fn.message({type: 'error', msg: '备注超出字数限制，请输入2000字以内！'});
                    return;
                }
            }
            //这四个数组是最后提交的时候，给后台的参数  freight
            var num = [];

            var inputObj = $('input[uid^="num_"]');
            var isMore = false;
            inputObj.each(function () {
                var $hiddenInfo = $(this).closest('tr').find('#hiddenInfo');
                productInfoObj = {};
                var inputArrivalNum = $.trim($(this).val());  //输入的到货数量
                if (!inputArrivalNum) {
                    inputArrivalNum = "0";
                }
                var total = parseInt($hiddenInfo.attr('data-allnum'), 10),
                    dxmProductId = $hiddenInfo.attr('data-dxmproductid'),
                    tempShowArrival = parseInt($(this).closest('tr').find('td:eq(2)').find('span').html(), 10); //到货数量
                if (total - tempShowArrival < 0) {
                    isMore |= true;
                }

                var $hjwSpan = $(this).closest('tr').find('span[name="changProductGoodsShelf"]');
                var newGoodShelfId = $hjwSpan.attr('data-newId');

                if (inputArrivalNum > 0) {
                    num.push(inputArrivalNum);

                    //组装商品信息
                    productInfoObj.dxmProductId = dxmProductId;    //商品id
                    productInfoObj.thisArrivalNum = inputArrivalNum;  //输入的到货数量
                    if (newGoodShelfId != undefined && null != newGoodShelfId && newGoodShelfId != 0 && '' != newGoodShelfId) {//选择的新货架位，没选就不传
                        productInfoObj.newGoodShelfId = newGoodShelfId;
                    }
                    //商品信息集合
                    productInfoList.push(productInfoObj);
                }
            });
            obj.id = purchasingId;           //采购单id
            obj.comment = comment;          //备注
            obj.arrivalInfo = JSON.stringify(productInfoList);  //将商品集合转成字符串

            //{id : 123, comment : "",
            // arrivalInfo : {productId : "", quantity : ""},
            // {}}
            if (isMore) {
                $('#loading').modal('hide');
                $.fn.message({type: 'error', msg: '到货数量不能超过采购数量！'});
                return;
            }
            var dhslbs = false;  //填写了到货
            $.each(num, function (index, value) {
                if (value) {
                    dhslbs |= true;
                }
            });

            if (dhslbs == false) {
                $.fn.message({type: 'error', msg: '到货数量不能都是空,请至少填写一项到货数量!'});
                $('#loading').modal('hide');
                return;
            }

            var dhslZerobs = false;  //填写了到货
            $.each(num, function (index, value) {
                if (value > 0) {
                    dhslZerobs |= true;
                }
            });

            if (dhslZerobs == false) {
                $.fn.message({type: "error", msg: "到货数量不能都是 0！"});
                $('#loading').modal('hide');
                return;
            }

            var isPrint = $('#isPrintThisTime').is(':checked') ? '1' : '0';
            $('#loading').modal('show');
            $.ajax({
                type: 'POST',
                url: requestUrl + 'dxmPurchasingNote/addArrival.json',
                data: {
                    obj: JSON.stringify(obj)
                },
                success: function (data) {
                    $('#loading').modal('hide');
                    if (data.msg) {
                        $.fn.message({type: "error", msg: data.msg});
                    } else {
                        var showMsg;
                        if (data.code == 2) {
                            if (data.qualityCheckStatus == 1) {
                                showMsg = "采购单" + podh + "已全部到货成功，已进入质检流程！";
                            } else {
                                showMsg = data.userConfig.putInStatus == "0" ? "采购单" + podh + "已全部到货入库，并已移入到「已完成」！" : "到货成功，等待入库人员入库";
                            }
                            $.fn.message({type: "success", msg: showMsg});
                            $('#loading').modal('hide');
                            $('#CreateShoppingListA').modal('hide');
                        } else if (data.code == 1) {
                            if (data.qualityCheckStatus == 1) {
                                showMsg = "采购单" + podh + "已部分到货成功，已进入质检流程！";
                            } else {
                                showMsg = data.userConfig.putInStatus == "0" ? "采购单" + podh + "已部分到货入库" : "到货成功，等待入库人员入库";
                            }
                            $.fn.message({type: "success", msg: showMsg});
                            $('#loading').modal('hide');
                            $('#CreateShoppingListA').modal('hide');
                        } else {
                            $.fn.message({type: "error", msg: podh + "采购单到货添加失败！"});
                            $('#loading').modal('hide');
                            $('#CreateShoppingListA').modal('hide');
                        }

                        if (isPrint == '1' && (data.code == 1 || data.code == 2)) {
                            typeof getPurchasingProduct === 'function' && getPurchasingProduct(purchasingId, productInfoList);
                            var printSkuLabelDialog = $('#batchPurchasingSkuLabel');
                            printSkuLabelDialog.modal('show');
                            printSkuLabelDialog.on('hidden.bs.modal',function () {
                                printSkuLabelDialog.find('#closeBtn').text('取消');
                            });
                        }
                    }
                    reloadPro(true);
                }
            });
        },

        /******************************批量到货***********************************/
        batchArrivePurchasing: function (e) {
            var trs = $(e).closest("table").find("tr[class='content']");
            for (var i = 0; i < trs.length; i++) {
                var input = $(trs[i]).find("input");
                if (!input) {
                    continue;
                }
                var historyNum = $(trs[i]).find("span[uid='historyNum']").text();
                var arriveNum = $(trs[i]).find("span[uid='quantity']").text();
                $(input).val(parseInt(arriveNum, 10) - parseInt(historyNum, 10));
            }
        },

        batchClearPurchasing: function (e) {
            var trs = $(e).closest("table").find("tr[class='content']");
            for (var i = 0; i < trs.length; i++) {
                var input = $(trs[i]).find("input");
                if (!input) {
                    continue;
                }
                $(input).val("");
            }
        },

        /**
         * 输入剩余到货数量
         * @param e
         */
        changePurchasingNum: function (e) {
            if (/[^0-9]/g.test($(e).val())) {//替换非数字字符
                var temp_amount = $(e).val().replace(/[^0-9]/g, '');
                $(e).val(temp_amount);
            }
            var history = $(e).closest("td").prev("td").find("span[uid='historyNum']");
            var historyNum = $(history).attr("nuid");
            var num = $(e).val();
            if (num > 0) {
                $(history).text(parseInt(num, 10) + parseInt(historyNum, 10));
            } else {
                $(history).text(historyNum);
            }

            var arriveNumber = $(e).closest("td").prev("td").find("span[uid='quantity']").text();
            if (parseInt(historyNum, 10) + parseInt(num, 10) > parseInt(arriveNumber, 10)) {
                $.fn.message({type: "error", msg: "「到货数量」不能大于「采购数量」，请重新填写！"});
                $(history).text(historyNum);
            }
        },

        removePurchasingNote: function (e) {
            var purchasingNoteId = $(e).closest("tr").attr("uid");
            $("tr[uid='" + purchasingNoteId + "']").detach();
        },

        //批量到货
        purchasingNoteArrive: function () {
            var purchasingNoteList = [];
            var trs = $("#batchArriveModal").find("#batchArriveTableId").find("tbody[id='batchArriveBody']").find("tr[class='header']");
            var flag = false;
            for (var i = 0; i < trs.length; i++) {
                var obj = {};   //采购单对象
                var productInfoList = [];     //采购单对象下的商品集合

                var purchasingId = $(trs[i]).attr("uid");		//采购单id
                var comment = $(trs[i]).find('input[name="noteComment"]').val();		//备注 comment字段

                var contentTrs = $(trs[i]).nextAll("tr[uid=" + purchasingId + "]");
                var count = 0;
                for (var j = 0; j < contentTrs.length; j++) {
                    var productInfoObj = {};						//单个商品
                    var tempPid = $(contentTrs[j]).attr("productId");      //商品id
                    var arriveNumInput = $(contentTrs[j]).find("td:eq(4)").find("input");
                    var tempNum;
                    if (arriveNumInput.length === 0) {
                        tempNum = '0';
                    } else {
                        tempNum = $(arriveNumInput).val();         //输入的到货数量
                    }
                    if (!tempNum || tempNum <= 0) {
                        count++;
                        if (count === contentTrs.length) {
                            $.fn.message({type: "error", msg: "请填写数量，采购单中不能全部为空！"});
                            return;
                        }
                        tempNum = '0';
                    }

                    var $hjwSpan = $(contentTrs[j]).closest('tr').find('span[name="changProductGoodsShelf"]');
                    var newGoodShelfId = $hjwSpan.attr('data-newId');

                    var historyNum = $(contentTrs[j]).find("td:eq(2)").find("span[uid='historyNum']").attr("nuid");
                    var quantity = $(contentTrs[j]).find("td:eq(2)").find("span[uid='quantity']").text();
                    if (parseInt(historyNum, 10) + parseInt(tempNum, 10) > parseInt(quantity, 10)) {
                        flag = true;
                        $.fn.message({type: "error", msg: "输入的数量超过可到货的数量！"});
                        return;
                    }
                    if (tempNum != '0') {
                        productInfoObj.dxmProductId = tempPid;    //商品id
                        productInfoObj.thisArrivalNum = tempNum;  //输入的到货数量
                        if (newGoodShelfId != undefined && null != newGoodShelfId && newGoodShelfId != 0 && '' != newGoodShelfId) {//选择的新货架位，没选就不传
                            productInfoObj.newGoodShelfId = newGoodShelfId;
                        }
                        productInfoList.push(productInfoObj);
                    }
                }
                obj.id = purchasingId;           //采购单id
                obj.comment = comment;          //备注
                obj.arrivalInfo = JSON.stringify(productInfoList);  //将商品集合转成字符串
                purchasingNoteList.push(obj);
            }
            $("#loading").modal("show");
            $.ajax({
                type: "POST",
                url: "dxmPurchasingNote/batchArrivePurchasingNote.json",
                data: {
                    purchasingNoteList: JSON.stringify(purchasingNoteList)
                },
                success: function (data) {
                    $('#loading').modal('hide');
                    var showMsg;
                    if (data.code > 0) {
                        if (data.qualityCheckStatus == 1) {
                            showMsg = "批量到货成功，已进入质检流程！";
                        } else {
                            showMsg = "批量到货完成！";
                        }
                        $.fn.message({type: "success", msg: showMsg});
                        $('#batchArriveModal').modal('hide');

                    } else if (data.code == -2) {
                        $('#batchArriveModal').modal('hide');
                        $.fn.message({type: "error", msg: "采购单" + podh + "中有商品正在盘点中，不能到货入库！"});

                    } else {
                        $('#batchArriveModal').modal('hide');
                        $.fn.message({type: "error", msg: "批量到货添加失败！"});
                    }
                    $('#batchArriveModal').modal('hide');
                    reloadPro();
                },
                error: function (err) {
                    $('#loading').modal('hide');
                    $.fn.message({type: "error", msg: "批量到货添加失败！"});
                    $('#batchArriveModal').modal('hide');
                }
            });
        },

        //到货历史显示
        arrivalHistory: function (id) {
            var table = $("<table class='myj-table mTop10' id='arrivalGoodsContent'></table>");
            var tableTh = "<tr><th>时间</th> <th>到货SKU&nbspX&nbsp数量</th> <th>状态</th> <th>入库编号</th></tr>";
            table.append(tableTh);
            if (id) {
                $.ajax({
                    type: "GET",
                    url: "dxmPurchasingNote/getWarehouseArrivalRecord.json",
                    data: {
                        "purchasingid": id
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.code == "-1") {
                            $('div[uid="receivingRecord"]').empty().append('<div style="text-align: center;line-height: 20px;" class="fW600">没有到货记录！</div>');
                            /*$.fn.message({type: "error", msg: "没有到货记录！"});*/
                            return;
                        }
                        // var cai = "<span class='fW600'>采购单号：" + data.list[0].purchasingNo + "</span>";
                        var tr = "";
                        for (var i = 0; i < data.list.length; i++) {
                            var recordState = data.list[i].recordState;
                            var state = '', no = data.list[i].recordNo || '';
                            if (recordState == 'in_warehouse') {
                                state = "入库";
                            } else if (recordState == 'wait_in_warehouse') {
                                state = "待入库";
                            }
                            tr += '<tr><td style="text-align: left;">' + purchasing.arrivalRenderTime(data.list[i].recordTime) + '</td>';
                            tr += '<td style="text-align: left;">' + data.list[i].skuAndNum + '</td>';
                            tr += '<td style="text-align: left;">' + state + '</td>';
                            tr += '<td style="text-align: left;">' + no + '</td></tr>';
                        }
                        table.append(tr);
                        // $('div[uid="receivingRecord"]').empty().append(cai).append(table);
                        $('div[uid="receivingRecord"]').empty().append(table);
                    }
                });
            }
        },

        //异常处理
        exceptionProcess: function(id) {
            $.post(requestUrl + 'warehouseException/getExceptionProcessByPurchasingId.htm', {
                purchasingId: id
            }, function(data) {
                $('div[uid="excepHand"]').empty().html(data);
            })
        },

        arrivalRenderTime: function (sj) {
            var date = new Date(parseInt(sj, 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes() < 10 ? "0" + (date.getMinutes()) : date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds();
            var milliseconds = date.getMilliseconds();
            return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        },

        viewWaitPayComment: function (id) {
            $('#procurementNotes').val("");
            $('#financialNotes').val("");
            $('#waitPayCommentContent').val('');
            $.ajax({
                type: "get",
                url: "dxmPurchasingNote/viewOnlyPurchasingNote.json",
                data: {
                    id: id
                },
                dataType: "json",
                success: function (data) {
                    if (data != null && data) {
                        if (data.comment || data.financeComment) {
                            var con = data.comment;
                            var fin = data.financeComment;
                            var color = data.commentColor;
                            var time = purchasing.arrivalRenderTime(data.commentTime);
                            $('#procurementNotes').val(con);
                            $('#financialNotes').val(fin);
                            $('#waitPayCommentContent').val(data.comment);

                            $("#commentColorDivP").find("a").each(function () {
                                $(this).removeClass("bgCommentFocus");
                                if ($(this).attr("data-val") == color) {
                                    $(this).addClass("bgCommentFocus");
                                }
                            });

                            var table = $('<table style="font-size:13px;"></table>');
                            var tableTh = '<tr style="background:#eee;" class="popover-contentTh"><th>时间</th> <th>内容</th><th>类型</th></tr>';
                            var tr = [];
                            if (data.comment) {
                                var $commentTr = $("<tr class='popover-contentTd'><td style='width: 130px;max-width: 130px;min-width: 130px;'><div>" + time + "</div></td>" +
                                    "<td><div class='purchasingCommentBox' style='word-break: break-all;width: 400px;'></div></td>" +
                                    "<td>采购备注</td></tr>");
                                $commentTr.find('.purchasingCommentBox').text(con);
                                tr.push($commentTr);
                            }
                            if (data.financeComment) {
                                var $financeCommentTr = $("<tr class='popover-contentTd'><td style='width: 130px;max-width: 130px;min-width: 130px;'><div>" + time + "</div></td>" +
                                    "<td><div class='purchasingCommentBox' style='word-break: break-all;width: 400px;'></div></td>" +
                                    "<td>财务备注</td></tr>");
                                $financeCommentTr.find('.purchasingCommentBox').text(fin);
                                tr.push($financeCommentTr);
                            }
                            table.append(tableTh).append(tr);
                            $('div[uid="remarksRecords"]').empty().append(table);
                        } else {
                            $('div[uid="remarksRecords"]').empty().append('<div style="text-align: center;line-height: 20px;" class="fW600">备注记录为空!</div>');
                        }
                    } else {
                        $('div[uid="remarksRecords"]').empty().append('<div style="text-align: center;line-height: 20px;" class="fW600">备注记录为空!</div>');
                    }
                }
            });
        },
        //查看审核记录
        viewAuditRecord:function(id){
            $.get("dxmPurchasingNote/getPaidById.json",{id:id},function (response) {
                if (response && response.dxm) {
                    var auditTime = response.dxm.auditTime,
                        auditComment = response.dxm.rejectComment;
                    if (auditComment) {
                        var table = $('<table style="font-size:13px;"></table>');
                        var tableTh = '<tr style="background:#eee;" class="popover-contentTh"><th>时间</th> <th>内容</th><th>类型</th></tr>';
                        var tr = "";

                        tr += "<tr class='popover-contentTd'><td style='width: 130px;max-width: 130px;min-width: 130px;'><div>" + purchasing.arrivalRenderTime(auditTime) + "</div></td><td><div style='word-break: break-all;width: 400px;'>" + auditComment + "</div></td><td>审核说明</td></tr>";
                        table.append(tableTh).append(tr);
                        $('div[uid="auditRecords"]').empty().append(table);
                    }else {
                        $('div[uid="auditRecords"]').empty().append('<div style="text-align: center;line-height: 20px;" class="fW600">审核记录为空!</div>');
                    }
                }
            });

        },

        // 变更记录
        changeRecord: function(id) {
            $('#loading').modal('show');
            $.get('dxmPurchasingNote/changeRecordById.json', {id: id}, function(data){
                $('#loading').modal('hide');
                var table = $("<table class='myj-table mTop10'></table>");
                var tableTh = "<tr><th>变更单号</th><th>状态</th><th>操作人</th><th>时间</th></tr>";
                table.append(tableTh);
                if (data.code) {
                    $('div[uid="changeRecords"]').empty().append('<div style="text-align: center;line-height: 20px;" class="fW600">没有变更记录！</div>');
                    return;
                }
                var tr = "";
                for (var i = 0; i < data.dataList.length; i++) {
                    var statusStr = data.dataList[i].statusStr,
                        no = data.dataList[i].taskNo || '';
                    tr += '<tr><td style="text-align: left;">'+no+'</td>';
                    tr += '<td style="text-align: left;">'+statusStr+'</td>';
                    tr += '<td style="text-align: left;">'+data.dataList[i].createName+'</td>';
                    tr += '<td style="text-align: left;">'+data.dataList[i].createTimeStr+'</td></tr>';
                }
                table.append(tr);
                $('div[uid="changeRecords"]').empty().append(table);
            });
        },

        paidRecord: function (id) {
            $.get(
                "dxmPurchasingNote/getPaidById.json",
                {
                    id: id
                },
                function (data) {
                    if (data.code == "-1" || data.dxm.dxmPurchasingPayOperateRecords.length == 0) {
                        $('div[uid="paymentRecord"]').empty().append('<div style="text-align: center;line-height: 20px;" class="fW600">没有付款记录！</div>');
                        return;
                    }
                    var cai = "<span class='fW600'>采购单号：<span id='purchasingNo'>" + data.dxm.purchasingNoAll + "</span></span>";
                    var table = $("<table class='myj-table mTop10'></table>");
                    var tableTh = '<tr><th>时间</th><th>流水号</th><th>金额</th><th>状态</th></tr>';
                    $('#purchasingNo').html(data.dxm.purchasingNoAll);
                    var tr = "";
                    var tempList = data.dxm.dxmPurchasingPayOperateRecords;
                    for (var i = 0, sum = tempList.length; i < sum; i++) {

                        var curstate = tempList[i].curState,
                            recordState = '';
                        if (curstate == 'noPay') {
                            recordState = '申请';
                        } else if (curstate == 'yesPay') {
                            recordState = '已付款';
                        } else if (curstate == 'quxiaoPay') {
                            recordState = '取消';
                        } else if (curstate == 'returnPre') {
                            recordState = '被打回';
                        }
                        var amount = parseFloat(tempList[i].amount).toFixed(4);
                        if (amount.endWith('00')) amount = (+amount).toFixed(2);
                        var applyType = '1';
                        if (tempList[i].dxmFinancePay != null) {
                            applyType = tempList[i].dxmFinancePay.applyType
                        }
                        var isApplyFee = applyType == '1' ? '' : '追加额外运费';
                        tr += '<tr><td style="text-align: left;">' + purchasing.arrivalRenderTime(tempList[i].updateTime) + '</td>';
                        tr += '<td style="text-align: left;">' + tempList[i].serialNo + '</td>';
                        tr += '<td style="text-align: left;">' + isApplyFee + '￥' + amount + '</td>';
                        tr += '<td style="text-align: left;">' + recordState + '</td></tr>';
                    }
                    table.append(tableTh).append(tr);
                    $('div[uid="paymentRecord"]').empty().append(cai).append(table);
                },
                'json'
            );
        },

         ajaxAccessUser: function (agentId, id, isUseChoose) {
            $.post('dxmPurchasingNote/getAccessUser.json', {}, function (data) {
                var idObj = $('#'+id);
                if (data) {
                    var $agentOption = '<option value="0">--请选择采购员--</option>';
                    $.each(data, function (i, j) {
                        $agentOption += "<option value='" + i + "'>" + j + "</option>";
                    });
                    idObj.empty().html($agentOption);
                    if (agentId) {
                        idObj.find('option[value="'+agentId+'"]').prop('selected', true);
                    } else {
                        var userUid = $('#userId').val();
                        idObj.find('option[value="'+userUid+'"]').prop('selected', true);
                    }
                    if (isUseChoose) {
                        idObj.chosen({
                            search_contains: true
                        });
                        idObj.trigger("chosen:updated");
                    }
                }
            })
        },

        // 编辑采购单之前增加验证逻辑
        editBefore: function (obj, pageType) {
            // 验证采购单存在与否
            var zt = $('#zt').val(),
                id =  $(obj).closest('tr').attr('id') ;

            $.ajax({
                url: requestUrl + 'dxmPurchasingNote/checkPurchasing.json',
                data: {id: id},
                async: false,
                success: function (data) {
                    if (data.code == 1) {
                        $('span[uid="checkMsg"]').text(data.msg);
                        $('button.checkPurchasing').attr('data-Id', id + '');
                        $('#checkPurchasing').modal('show');
                        return;
                    }
                    window.open(requestUrl + 'dxmPurchasingNote/edit.htm?pageType=' + pageType + '&id=' + id);
                }
            })
        },

        closeModal: function (obj) {
            var zt = $('#zt').val(), id = $(obj).attr('data-Id');
            if (zt == 'wait_pay') {
                $('tr[id="'+id+'"]').remove()
            } else {
                $('tr[purchasingId="'+id+'"]').prev('tr').remove();
                $('tr[purchasingId="'+id+'"]').remove();
            }
        },

        // 列表页展开动作
        viewPro: function (obj) {
            var dataType = $(obj).attr('data-type'),
                id = $(obj).closest('tr').attr('purchasingId'),
                $tr = $('#detail_' + id),
                $child = $tr.children();

            $('#productsourcetype').val($(obj).attr('productsourcetype'));

            !!+dataType ? $tr.addClass('myj-hide') : (function () {
                if (!+$child.find('.details-list').length) {
                    $.post('dxmPurchasingNote/commDetail.json', {ids: id}, function (data) {
                        var tableStr = purchasing.commPurDetail(data);
                        $child.html(tableStr);
                        $('[data-toggle="popover"]').popover();
                        initFindGoods('imgDivIn', 'pageState');//注册找货源
                        purchasing.lightShowSkuDetail($tr, 1);//高亮显示搜索的sku所对应的那个产品信息
                    });
                }

                $tr.removeClass('myj-hide');
            })();
            $(obj).attr('data-type', !+dataType ? 1 : 0);
        },

        //高亮显示搜索的sku所对应的那个产品信息
        lightShowSkuDetail: function ($tr, type) {
            var searchType = $('#' + (type ? 'alibabaSearchType' : 'searchType')).val(),
                searchValue = $.trim($('#searchValue').val()).replace(/，/g, ','),
                isSearchSku = type ? +searchType === 5 : +searchType === 2;

            $('.detailsItemDiv.bg-yellow-imp').removeClass('.bg-yellow-imp');//先初始化清除历史样式
            if (isSearchSku && searchValue) {
                $.each(searchValue.split(','), function (i, j) {//使用循环方式比对，不要使用选择器，防止sku特殊字符时报错的问题
                    var skuStr = $.trim(j);

                    if (skuStr) {
                        var $detailsItemDiv;
                        if ($tr === null) {
                            $detailsItemDiv = $('.detailsItemDiv');
                        } else {
                            $detailsItemDiv = $tr.find('.detailsItemDiv');
                        }
                        $detailsItemDiv.each(function () {
                            if (skuStr === $.trim($(this).attr('data-sku'))) $(this).addClass('bg-yellow-imp');//加上高亮效果
                        });
                    }
                });
            }
        },

        // 货品详情公用部分
        commPurDetail: function (data, all) {
            var productsourcetype = $('#productsourcetype').val();
            if (data) {
                var oneTable = '', tableObj = $('#purchasingDetail').html(),
                    skuSpan = '<span class="inline-block h40 detailsCon" data-container="body" ' +
                        'data-toggle="popover" data-trigger="hover" data-placement="bottom" data-html="true" data-content="&{sku}">' +
                        '<a class="no-new-line2 maxW135" href="dxmCommodityProduct/index.htm?id=&{id}" target="_blank">&{sku}</a></span>',
                    noSkuSpan = '<span class="detailsCon" data-container="body" ' +
                        'data-toggle="popover" data-trigger="hover" data-placement="bottom" data-html="true" data-content="&{sku}">&{sku}</span>',
                    nameSpan = '<span class="detailsCon limingcentUrlpic" data-container="body" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-html="true" data-content="&{name}">&{name}</span><br/><span class="f-red &{isShow}">未配对</span>',
                    skuCodeSpan = '<span class="detailsCon" data-container="body" ' +
                    'data-toggle="popover" data-trigger="hover" data-placement="bottom" data-html="true" data-content="&{skuCode}">&{skuCode}</span>';
                $.each(data, function (a, b) {
                    var tableStr = '';
                    $.each(b.noteProduct, function (i, j) {
                        if(productsourcetype !== undefined && !+productsourcetype) {// 没有权限，不需要显示来源
                            sourceUrlStr = '';
                        } else if (j.sourceUrl) { // 处理来源
                            var sourceUrlStr = '', sourceUrlLiStr = '';
                            if (j.sourceUrl.indexOf('|') !== -1) {
                                var sourceUl = '<a href="javascript:" class="dropdown-toggle" data-toggle="dropdown" type="button" onclick="">来源<span class="caret"></span></a><ul class="dropdown-menu pull-left" role="menu" aria-labelledby="">',
                                    sourceLi = '<li role="presentation"><a href="javascript:" data-url="&{sourceUrl}" onclick="purchasing.redirectUrl(this);">来源&{index}：&{sourceUrlName}</a></li>';
                                var sourceArr = j.sourceUrl.split('|');
                                $.each(sourceArr, function (m, k) {
                                    if(k){
                                        sourceUrlLiStr += sourceLi.format({
                                            sourceUrl: k,
                                            index: m + 1,
                                            sourceUrlName: getSourceName(k)
                                        })
                                    }
                                });

                                sourceUrlStr = sourceUl + sourceUrlLiStr + '</ul>';

                            } else {
                                sourceLi = '<a href="javascript:" data-url="&{sourceUrl}" onclick="purchasing.redirectUrl(this);">&{sourceUrlName}</a>';
                                sourceUrlStr += sourceLi.format({
                                    sourceUrl: j.sourceUrl,
                                    sourceUrlName: getSourceName(j.sourceUrl)
                                })
                            }
                        }

                        var skuSpanStr = j.productId ? skuSpan.format({
                            sku: j.sku,
                            id: j.productId
                        }) : noSkuSpan.format({
                            sku: j.sku
                        }),
                        skuStr = j.sku;

                        var nameSpanStr = nameSpan.format({
                            name: j.name || '',
                            isShow: j.productId ? 'hide' : ''
                        });

                        var skuCodeSpanStr = skuCodeSpan.format({
                            skuCode: j.skuCode
                        });

                        var price = (+j.price).toFixed(4);
                        if (price.endWith('00')) price = (+price).toFixed(2);
                        var tableData = {
                            isTableRight: (i + 1) % 3 !== 0 ? 'details_tableRight' : '',
                            isMark: j.isAllArrival ? 'relative ready' : '',
                            mainImg: j.imgUrl ? getPicRealUrl(j.imgUrl) : '/static/img/kong.png',
                            sourceUrl: sourceUrlStr ? $('#sourceUrl').html().format({sourceUrl: sourceUrlStr}) : '',
                            skuSpan: skuSpanStr,
                            id: j.productId,
                            nameSpan: nameSpanStr,
                            skuCode: skuCodeSpanStr,
                            alreadyNum: j.alreadyNum || 0,
                            quantity: j.quantity,
                            price: price,
                            skuStr: skuStr
                        };

                        tableStr += tableObj.format(tableData);
                    });

                    tableStr = '<div class="details-list clear-fix">' + tableStr + '</div>';

                    if (all) {
                        var id = b.id,
                            dataTypeObj = $('tr.purchaseTr#'+id).find('.productShowAllHtml'),
                            dataType = $(dataTypeObj).attr('data-type'),
                            $tr = $('#detail_' + id),
                            $child = $tr.children();

                        $child.html(tableStr);
                        $(dataTypeObj).attr('data-type', !+dataType ? 1 : 0);
                        $tr.removeClass('myj-hide');
                    } else {
                        oneTable = tableStr;
                        return false;
                    }
                });

                return oneTable;
            }
        },

        // 来源重定向
        redirectUrl: function (obj) {
            var sourceUrl = $(obj).attr('data-url');
            if (sourceUrl) {
                if (sourceUrl.indexOf('detail.1688.com') !== -1 ||
                    sourceUrl.indexOf('item.taobao.com') !== -1 ||
                    sourceUrl.indexOf('detail.tmall.com') !== -1) {
                    sourceUrl = encodeURIComponent($.trim(sourceUrl));
                    var wo = window.open('about:blank', '_blank');
                    wo.location.href = '/productSource/redirectUrl.json?module=purchasing&sourceUrl='+sourceUrl;
                } else {
                    window.open(sourceUrl, '_blank');
                }
            }
        },

        /***  采购单详情 页面下方操作方法 ***/
        // 返回
        backToPaymentListFn: function () {
            W.close();
        },

        // 付款备注弹层
        showCommetDiaLog: function (payId) {
            var $financeCommentDetail = $('#financeCommentDetail'),
                $financeComment = $('#financeComment'),
                curComment = $('.financeCommentData').val();

            //绑定btn
            $financeCommentDetail.val('');
            $financeComment.find('[name="sureBtn"]').attr('onclick', 'purchasing.editComment("' + payId + '")');
            if (curComment) {
                $financeCommentDetail.val(curComment);
            } else {
                $financeCommentDetail.attr('placeholder', '请填写您要备注的内容');
            }
            $financeComment.modal('show');
        },

        // 确认编辑备注
        editComment: function (payId) {
            var comment = $('#financeCommentDetail').val();

            MYJ.ajax({
                url: 'dxmFinancePay/editComment.json',
                data: {
                    id: payId,
                    comment: comment
                },
                success: function (data) {
                    if (!data.code) {
                        //成功
                        MYJ.message.success('修改备注成功！');
                        $('#financeComment').modal('hide');
                        setTimeout(function () {
                            W.location.reload();
                        }, 3500);
                    } else {
                        MYJ.message.error(data.msg);
                    }
                }
            });
        },

        // 删除数据
        deletePayMethod: function (id) {
            var titleHtml = '删除确认',
                contentHtml = '<div>删除后，该条付款数据将清空。</div><div>你确定要删除该付款记录吗</div>';

            MYJ.confirm({
                type: 'error',
                title: titleHtml,
                enter: '确认',
                content: contentHtml,
                callback: function (v) {
                    if (v) {
                        MYJ.ajax({
                            url: 'dxmFinancePay/deletePayment.json',
                            data: {
                                id: id
                            },
                            success: function (res) {
                                if (!+res.code) {
                                    MYJ.message.success('删除成功！');
                                    setTimeout(function () {
                                        W.location.reload();
                                    }, 3500);
                                }
                            }
                        });
                    }
                }
            });
        },

        // 显示1688标记付款
        signOnePayment1688: function (type, pId, orderId) {
            if (!orderId) {
                MYJ.message.error('无效的1688单号！');
                return;
            }
            $.ajaxSettings.async = false;
            $.post(requestUrl + 'dxmFinancePay/checkRedirect.json', {id: pId}, function (data) {
                if (data && data.orderId) {
                    //运费申请无需跳转
                    var wo = W.open('about:blank', '_blank');
                    wo.location.href = 'https://trade.1688.com/order/order_detail.htm?orderId=' + data.orderId;
                }
            });
            purchasing.signOnePayment(type, pId);
        },

        // 单个标记付款
        signOnePayment: function (type, pId) {
            if (+type === 0) {
                //初始化  0（手动付款单）
                var $paySelectAccount0 = $('#paySelectAccount0');

                $paySelectAccount0.find('[name = showName]').val('付款');
                $paySelectAccount0.find('[name="sureBtn"]').attr('onclick', 'purchasing.sureSingleOnePayment("' + type + '","' + pId + '")');
                $paySelectAccount0.modal('show');
            } else if (+type === 1) { //1688采购
                var $payPurchaseOrder = $('#payPurchaseOrder');

                $payPurchaseOrder.find('#batchPayIndentID').html('');
                purchasing.getPayAmountOrder('#defaultAccountID');
                //移除关闭的内容
                $payPurchaseOrder.find('#payPurchaseCloseBtn').removeAttr('onclick');//移除点击事件
                $payPurchaseOrder.find('[name="sureBtn"]').attr('onclick', 'purchasing.sureSingleOnePayment("' + type + '","' + pId + '")');
                $payPurchaseOrder.modal('show');
            } else {
                //初始化 1、2(采购单付款)
                var $paySelectAccount1 = $('#paySelectAccount1');

                $paySelectAccount1.find('.modal-title').html('付款');
                $paySelectAccount1.find('[name="sureBtn"]').attr('onclick', 'purchasing.sureSingleOnePayment("' + type + '","' + pId + '")');
                //验证是否要跳转
                purchasing.showPurchaseSlect();
            }
        },

        // 确认单个标记付款
        sureSingleOnePayment: function (type, pId) {
            var payAccountId = +type === 1 ? $('#defaultAccountID').val() : $('#myAccount').val();

            MYJ.ajax({
                url: 'dxmFinancePay/singleOnePayment.json',
                dataType: 'json',
                data: {
                    id: pId,                               //账户id
                    payAccountId: payAccountId             //标记付款的ids
                },
                async: false,
                success: function (data) {
                    if (!data.code) {
                        MYJ.message.success('标记付款成功');
                        if (+type === 0) {
                            $('#paySelectAccount0').modal('hide');
                        } else if(+type === 1){
                            $('#payPurchaseOrder').modal('hide');
                        }else{
                            $('#paySelectAccount1').modal('hide');
                        }
                        setTimeout(function () {
                            W.location.reload();
                        }, 3500);
                    } else {
                        if (data.payUrl) {
                            var wo = W.open('about:blank', '_blank');
                            wo.location.href = data.payUrl;
                            return;
                        }
                        MYJ.message.error(data.msg);
                    }
                }
            });
        },

        // 选择付款账号弹层
        showPurchaseSlect: function () {
            purchasing.getPayAmountOrder('#myAccount');
            $('#paySelectAccount1').modal('show');
        },

        // 请求获取付款账号
        getPayAmountOrder: function(myAccountID){
            MYJ.ajax({
                url: 'dxmFinanceAccount/getAccountList.json',
                data: {},
                success: function (data) {
                    if (!data.code) {
                        //成功
                        $(myAccountID).empty().append('<option value="0">默认账号</option>');
                        var optionStr = '';

                        $(data.accountList).each(function (i, obj) {
                            optionStr += '<option value="' + obj.idStr + '">' + obj.accountName + '</option>';
                        });
                        $(myAccountID).append(optionStr);
                    }
                }
            });
        },

        // 显示驳回的弹层
        showRejectPayment: function (payType, payId, applayType) {
            var $rejectPaymentDialog = $('#rejectPaymentDialog');

            if (+payType === 0 || +applayType === 2) {
                $rejectPaymentDialog.find('span[name="isBackName"]').html('删除');
            } else {
                $rejectPaymentDialog.find('span[name="isBackName"]').html('驳回');
            }

            $('#sureReject').attr('onclick', 'purchasing.rejectPayment(' + payType + ',\'' + payId + '\')');
            $rejectPaymentDialog.modal('show');
        },

        // 确认驳回付款
        rejectPayment: function (payType, payId) {
            MYJ.ajax({
                url: 'dxmFinancePay/rejectApplyPayment.json',
                data: {
                    id: payId                   //标记驳回的ids
                },
                success: function (data) {
                    if (!data.code) {
                        MYJ.message.success('操作成功！');
                        $('#rejectPaymentDialog').modal('hide');
                        setTimeout(function () {
                            W.close();
                        }, 3500);
                    } else {
                        MYJ.message.error(data.msg);
                    }
                }
            });
        },

        //标记付款
        signPayOrderMethod: function (id) {
            MYJ.ajax({
                url: 'dxmFinancePay/singlePayment.json',
                data: {
                    id: id,                               //账户id
                    payAccountId: 0                       //标记付款的ids
                },
                async: false,
                success: function (data) {
                    if (!data.code) {
                        MYJ.message.success('标记付款成功');
                        setTimeout(function () {
                            W.location.reload();
                        }, 3500);
                    } else {
                        MYJ.message.error(data.msg);
                    }
                }
            });
        },

        // 编辑 付款单
        editPayMent: function (id, obj) {
            //初始化弹层
            var $addPayReceipt = $('#addPayReceipt'),
                $payAccountId = $('#payAccountId');

            $payAccountId.first();
            $('#payAmount').val('');
            $('#financeContent').val('');
            $addPayReceipt.find('.modal-title').html('编辑付款单');

            MYJ.ajax({
                url: 'dxmFinancePay/getFinancePayDetail.json',
                data: {
                    id: id
                },
                success: function (data) {
                    if (!data.code) {
                        //成功
                        $payAccountId.empty().append('<option value="-1">选择付款账户</option> <option value="0">默认账号</option>');
                        var optionStr = '';

                        $(data.accountList).each(function (i, obj) {
                            optionStr += '<option value="' + obj.idStr + '">' + obj.accountName + '</option>';
                        });
                        $payAccountId.append(optionStr);
                        $payAccountId.val(data.dxmFinancePay.financeAccountIdStr);
                        $('#payAmount').val(data.dxmFinancePay.amount);
                        $('#financeContent').val(data.dxmFinancePay.comment);

                        if (!$payAccountId.val() || $payAccountId.val() === null) $payAccountId.first();
                    }
                }
            });
            $addPayReceipt.find('button[name="btnSure"]').attr('onclick', 'purchasing.saveEdit(0,"' + id + '")');
            $addPayReceipt.find('button[name="btnSureAndPay"]').attr('onclick', 'purchasing.saveEdit(1,"' + id + '")');
            $addPayReceipt.modal('show');
        },

        // 保存已编辑的付款单
        saveEdit: function (type, id) {
            var payAccountId = $('#payAccountId').val(),
                payAmount = $('#payAmount').val();

            if (!payAccountId || payAccountId < 0) {
                MYJ.message.error('请选择付款账号！');
                return;
            }
            if (payAmount <= 0) {
                MYJ.message.error('请输入付款金额！');
                return;
            }

            MYJ.ajax({
                url: 'dxmFinancePay/saveEditOurPayReceipt.json',
                data: {
                    type: type,
                    payAccountId: payAccountId,
                    payAmount: payAmount,
                    comments: $('#financeContent').val(),
                    id: id
                },
                success: function (data) {
                    if (!data.code) {
                        MYJ.message.success('编辑付款单成功"！');
                        $('#addPayReceipt').modal('hide');
                        setTimeout(function () {
                            W.location.reload();
                        }, 3500);
                    } else {
                        MYJ.message.error(data.msg);
                    }
                }
            });
        }
    }
})(jQuery, document, window);
//采购选择商品弹层处理
var purProposal = (function($,a,b){
    var idProposals = []; //已选商品ID
    var idProposalsOldDel = []; //已删除ID
    var selSingleStr = ' <div class="pur-sel-single purSelSingle" id=selectDxmProductli_&{idStr} data-has="0" data-id="&{idStr}"><div class="commodity"><div class="commodity-img">' +
        '<div class="img-out"><img class="img-css" src="&{imgUrl}" /></div></div><div class="commodity-con"><div class="proSku">&{sku}</div>' +
        '<div class="gray-c proName">&{name}</div></div></div><a class="glyphicon glyphicon-trash pur-single-del" onclick="purProposal.purSelDelSingle(this);" href="javascript:"></a></div>';
    var selSingleStrAdd = ' <div class="pur-sel-single purSelSingle" id=selectDxmProductli_&{idStr} data-has="1" data-id="&{idStr}"><div class="commodity"><div class="commodity-img">' +
        '<div class="img-out imgOut"><img class="img-css" src="&{imgUrl}" /></div></div><div class="commodity-con"><div class="proSku"></div>' +
        '<div class="gray-c proName"></div></div></div><a class="glyphicon glyphicon-trash pur-single-del" onclick="purProposal.purSelDelSingle(this);" href="javascript:"></a></div>',
        selSingleGoodStr = '<div class="p5 pull-left imgHomeSm purSelSingle" id=selectDxmProductli_&{idStr}  data-has="0" data-id="&{idStr}" >' +
        '<span class="aMakeRemoveBtn closeBadge purSelDelBtn"></span>' +
        '<div class="imgDivIn w50 h50-imp">' +
        '<img class="imgCss" src="&{imgUrl}"></div>' +
        '<div class="productImgSku">&{sku}</div></div>';

    $(a).off('click','#selProProposal .purSelDelBtn');
    $(a).on('click','#selProProposal .purSelDelBtn', function () { //添加商品移除单个
        var $pageType = $('#pageType'),
            pageType = $pageType ? +$pageType.val() : 1;
        /*
         * pageType
          * 1：手工采购单 2：同步1688订单
          * 3: 1688 多供应商（入口：1688一键下单，1688采购 创建多供应商订单 PS: 不可切其他模式）
          * 4: 编辑1688订单（同步1688订单后）
          * 5: 单供应商 （创建多供应商后编辑 Ps:多供应商创建后拆分成多个单供应商单子）
          * 6: 1688 多供应商（入口：[手动采购 创建采购单] / [1688采购 添加现有订单] 切换 下单方式 为 "创建1688采购单" 可切回手工采购和同步订单）
          * */
        if (pageType !== 3 && pageType !== 6) {
            purProposal.purSelDelSingle(this);
        } else {
            var liId = $(this).closest('.purSelSingle').attr('data-id');
            $('#ida_' + liId).html('<span>选择</span>');
            MULTI_SUPPLIER.delSelectTrProposal(liId);
        }
    });
    $(a).off('click', '.purSelDelAllBtn');
    $(a).on('click', '.purSelDelAllBtn', function(){ //添加商品移除全部
        // 1688采购多供应商 清空全部
        var $pageType = $('#pageType'),
            pageType = $pageType ? +$pageType.val() : 1;
        if (pageType === 3 || pageType === 6) {
            MULTI_SUPPLIER.removeAllGoods(this);
            return;
        }
        purProposal.purSelDelAll(this);
    });
    $(a).off('keyup','form.doNotSubmit input[type="text"]');
    $(a).on('keyup','form.doNotSubmit input[type="text"]',function(e){
        var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if (keyCode == 13) {
            $(this).closest('div').find('button[type="submit"]').click();
        }
    });

    return {
        //初始化分类
        init: function(){
            //初始化选择分类
            var treeJson = purProposal.getTreeForCreateNoteAddPro(); // 初始化树的数组数据

            $('#variFullCidForAll').dxmTree({
                data: treeJson,
                isBtn: true, //是否是移动分类按钮注册，如果是则会把分类树节点插入到调用分类树注册的节点后面，如果不是则分类树节点插入到调用分类树注册的节点里面
                searchClass: 'p-right12 p-left12', //搜索节点的class样式
                activeId: '', //默认选中的分类树选项id，如果传空则默认不选中
                clickCall: function(event, id, nodeData){ //分类树选项点击回调事件
                    purProposal.showCatagoryNameAdd(id, nodeData);
                }
            });
        },
        //创建采购单的时候 添加商品  弹出选择商品界面
        addPurProProposal: function (obj, call) {
            var _this = this,
                $loading = $('#loading'),
                type = $(obj).attr('data-type'), //获取点击位置
                $modal = $('#quoteProductModal'),
                $purNote = type === 'alibaba' ? $('#alibabaCreatePurchasingNote') : $('#createPurchasingNoteDiv'),
                selechValueStr = '多个采购单号用逗号隔开，最多支持200个';

            if (type !== 'alibaba') {
                switch (+type) {
                    case 1:
                        selechValueStr = '多个SKU间用逗号隔开，最多支持200个';
                        break;
                    case 3:
                        selechValueStr = '多个商品编码间用逗号隔开，最多支持200个';
                        break;
                    default:
                        selechValueStr = '';
                        break;
                }
            }

            idProposalsOldDel = [];
            if($("#ckwzId").val() === -1){
                $.fn.message({type: "error", msg: "请选择仓库后，再添加商品！"});
                return;
            }
            $loading.modal('show');
            $modal.find('#searchProposalSelectType').val("1"); //搜索类型
            $modal.find('#searchProposalSelectValue').val('').attr('placeholder','多个SKU间用逗号隔开，最多支持200个'); //搜索的值
            $modal.find('#quoteModalProposalSkuId').addClass("tab-active");
            $modal.find('#quoteModalProposalSkuCodeId').removeClass("tab-active");
            $modal.find('#quoteModalProposalNameId').removeClass("tab-active");
            $modal.find('#variFullCidForAll #catagoryFullName').attr('groupid', '').html('选择分类');
            $modal.find('.myjTreeNode.active').removeClass('active');
            $modal.find('[uid="productSearchType"]').removeClass("myj-hide");

            $modal.find('[uid="alreadyAllProProduct"]').addClass("tab-check");
            $modal.find('[uid="alreadyGhsProProduct"]').removeClass("tab-check");
            $modal.find("#alreadyAllProProduct").removeClass("myj-hide");
            $modal.find("#alreadyGhsProProduct").addClass("myj-hide");
            $modal.find('#catagoryHiddenId').val('');

            _this.ajaxGetProductsProposal(type); //获取要选择采购单的商品
            _this.changeTabProposalSelectSku('all');

            //判断选择是否是无供货商，不是加载
            $modal.find('#searchGhsProposalSelectType').val("1");
            $modal.find('#searchGhsProposalSelectValue').val('').attr('placeholder', selechValueStr);
            $modal.find('#quoteGhsModalProposalSkuId').addClass("tab-active");
            $modal.find('#quoteGhsModalProposalNameId').removeClass("tab-active");

            var ghsProposalId = '';
            if(type === "shoudong"){ //获取手动采购中创建、编辑，待到货创建页面的供货商id
                ghsProposalId = $("#ghsId").val();
                $("#ghsProposalId").val(ghsProposalId);
            }else if(type === "jihua"){ //采购计划中供货商商品tab隐藏
                $("[uid='alreadyGhsProProduct']").hide();
            }else{ //获取采购建议中备货、缺货、1688采购建议的供货商id
                ghsProposalId = $purNote.find('.detailsModalTabChange').attr('uid').split('_')[1];
            }
            if(type !== "jihua"){//除采购计划不需要获取供货商商品外，其他都需要
                _this.ajaxGetSupplierProducts(ghsProposalId,type); //获取要选择采购单的商品
            }
            _this.getChooseProductToView(type); //将已经选择的展示到页面上
            $modal.find("#selProProposalNum").html(idProposals.length); //添加产品数量处理
            $loading.modal('hide');
            $modal.find('.addPurProposalBtn').attr('data-type', type ? type : "");
            $modal.customModal('show');
            MULTI_SEARCH && MULTI_SEARCH.init(['商品SKU', '商品编码'], '' , {
                boxClassName: '#addPurProProposalSearch'
            }); //初始化多个搜索 textarea
            MULTI_SEARCH.setPlaceholder('多个搜索请用回车换行(无需逗号结尾)，最多支持200个');
            //回调
            call && typeof call === 'function' && call();
        },
        quoteProModalClose: function(){ //选择商品弹层关闭
            $('#quoteProductModal').customModal("hide");
        },
        //获取要选择采购单的商品(全部)
        ajaxGetProductsProposal: function (type) {
            var /*flag = type,*/
                $purNote = type === 'alibaba' ? $('#alibabaCreatePurchasingNote') : $('#createPurchasingNoteDiv'),
                uid = $purNote.find('.detailsModalTabChange').attr('uid'),
                trObj = $purNote.find('#purchasingProposal_'+uid+' > tbody > tr'),//获取采购建议中备货、缺货、1688采购建议弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                warehouseId = '';
                if(uid){
                    warehouseId = uid.split("_")[0]
                }
            if(type === 'shoudong'){ //获取手动采购创建、编辑，待到货创建弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                trObj = $purNote.find("#tjspxqTableId > tbody > tr");
            }else if(type === 'jihua'){//获取采购计划弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                trObj = $purNote.find("#purchasePlanContent > tr");
            }
            idProposals = [];
            trObj.each(function(){
                idProposals.push($(this).attr('id'));
            });

            $.ajax({
                type: "POST",
                url: "purchasingProposal/getProductsPageList.htm",
                data: {
                    pageNo: 1,
                    pageSize: 50,
                    selectIds: idProposals.join(),
                    /* flag: flag,*/
                    warehouseId: warehouseId

                },
                dataType: "html",
                success: function (data) {
                    $('#quoteProductModal').find('#selectProposalPageList').html(data);
                }
            });
        },
        //获取要选择采购单的商品（供货商）
        ajaxGetSupplierProducts: function (supplierId,type) {
            var $purNote = type === 'alibaba' ? $('#alibabaCreatePurchasingNote') : $('#createPurchasingNoteDiv'),
                uid = $purNote.find('.detailsModalTabChange').attr('uid'),
                trObj = $purNote.find('#purchasingProposal_'+uid+' > tbody > tr'),//获取采购建议中备货、缺货、1688采购建议弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                warehouseId = '';

            if(uid){
                warehouseId = uid.split("_")[0]
            }
            if(type === 'shoudong'){ //获取手动采购创建、编辑，待到货创建弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                trObj = $purNote.find("#tjspxqTableId > tbody >tr");
            }else if(type === 'beforeEdit'){//获取1688采购创建、下单状态编辑、待到货和已完成再次购买弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                trObj = $purNote.find("#alibabaOrderProductTbody >tr");
            }else if(type === 'afterEdit'){//获取1688采购审核状态中追加弹层列表中的信息，用来在全屏弹层中列表页显示已选择状态
                trObj = $purNote.find("#aliOrderAfterEditDivRight > table > tbody > tr");
            }
            idProposals = [];
            trObj.each(function(){
                if($(this).attr('id')) idProposals.push($(this).attr('id'));
            });
            $.ajax({
                type: 'post',
                url: 'dxmSupplierProductRelation/getProductsForPurPropoalProRelPageList.htm',
                data: {
                    pageNo: 1,
                    pageSize: 50,
                    supplierId: supplierId,
                    selectIds: idProposals.join(),
                    warehouseId: warehouseId
                },
                dataType: 'html',
                success: function (data) {
                    $('#quoteProductModal').find('#selectGhsProposalPageList').html(data);
                }
            });
        },
        //将已经选择的展示到页面上
        getChooseProductToView: function (type) {
            var $modal = $('#quoteProductModal'),
                $selProProposal = $modal.find('#selProProposal'),
                $purNote = type === 'alibaba' ? $('#alibabaCreatePurchasingNote') : $('#createPurchasingNoteDiv'),
                uid = $purNote.find('.detailsModalTabChange').attr('uid'),
                trObj = $purNote.find('#purchasingProposal_'+uid+' > tbody > tr'); //获取采购建议中备货、缺货、1688采购建议弹层列表中的信息，用来在全屏弹层中列表页回显商品

            $selProProposal.empty(); //清空已选信息
            if(type == 'shoudong'){//获取手动采购创建、编辑，待到货创建弹层列表中的信息，用来在全屏弹层中列表页回显商品
                trObj = $purNote.find("#tjspxqTableId > tbody >tr");
            }else if(type == 'jihua'){//获取采购计划弹层列表中的信息，用来在全屏弹层中列表页回显商品
                trObj = $purNote.find("#purchasePlanContent >tr");
            }
            idProposals = [];
            trObj.each(function(){
                idProposals.push($(this).attr('id'));
            });
            $.ajax({
                type: 'get',
                url: 'dxmPurchasingNote/getProductByIds.json',
                data: {
                    ids: idProposals.join()
                },
                dataType: 'json',
                success: function (data) {
                    if (data.list && data.list.length > 0) {
                        var li = '';
                        $.each(data.list, function (i, j) {
                            data.list[i].imgUrl = j.imgUrl !== "" ? MYJ.getImgReplaceUrl({url: getTinyPicRealUrl(j.imgUrl)}) : "static/img/kong.png";
                            data.list[i].name = j.name || '';
                            li += selSingleStr.format(data.list[i]);
                        });
                        $selProProposal.append($(li));
                        if(type == 'alibaba') {
                            trObj.each(function (si, sj) {
                                $(".purSelSingle")[si].setAttribute("num", $(sj).find('#purNum_'+idProposals[si]).val());
                            });
                        }else if(type == 'jihua'){
                            trObj.each(function (si, sj) {
                                $(".purSelSingle")[si].setAttribute("num", $(this).find('[uid="purchasePlanNumber"]').val());
                            });
                        }
                    }
                }
            });
        },
        //搜索类型切换
        setSelectSearchType: function(obj){
            var $modal = $('#quoteProductModal'),
                $obj = $(obj),
                type = $obj.data('type'),
                selechValueStr = '';

            switch (+type) {
                case 1:
                    selechValueStr = '多个SKU间用逗号隔开，最多支持200个';
                    break;
                case 3:
                    selechValueStr = '多个商品编码间用逗号隔开，最多支持200个';
                    break;
                default:
                    selechValueStr = '';
                    break;
            }

            $modal.find("#searchProposalSelectType").val(type);
            $modal.find("#searchProposalSelectValue").attr("placeholder", selechValueStr);
            $obj.closest("td").find(".tab-active").removeClass("tab-active");
            $obj.addClass("tab-active");
            var $select = $('#searchDialogMode');
            if ($select.length === 0) {
                // 等于0，说明是采购计划
                $select = $('#searchMode');
            }
            if (+type === 1 || +type === 2){
                //采购订单、采购建议和采购计划共用了这个方法
                $select.removeClass('myj-hide');
            } else{
                $select.addClass('myj-hide');
            }
            MULTI_SEARCH.closeText();
        },
        //选择商品处理
        selectProProposal: function (id, obj, add) {
            var $proContent = $('#alibabaSyncPurchasingBox').find('.proContent[data-proId="'+id+'"]');
            if($proContent.length && +$proContent.attr('data-add') === 0){//这里是1688同步采购单的添加商品弹层中做移除操作时的验证
                $.fn.message({type : 'error', msg : '该商品和当前订单产品已建立配对关系,无法移除!'});
                return;
            }
            var _this = this,
                $selProProposal;

            if ($('#hasSearchOverSeaPrepareDataID').val() === 'seaPrepare') { //海外仓备货建议
                $selProProposal = $('#quoteProductModal #selProProposal');
            } else {
                $selProProposal = $('#selProProposal');
            }

            if ($selProProposal.find('#selectDxmProductli_' + id).attr('id') !== undefined) {
                $(obj).html('<span>选择</span>');
                _this.delSelectTrProposal(id,add);
                return;
            } else {
                $(obj).html('<span class="f-green">已选择</span>');
            }
            var imgUrl = $('#hiddenMainImagez_' + id).val(),
                data = {
                    idStr: id,
                    imgUrl: imgUrl === '' ? 'static/img/kong.png' : MYJ.getImgReplaceUrl({url: imgUrl})
                };
            var $selSingleStrAdd = $(selSingleStrAdd.format(data)),
                $quoteProductModal = $('#quoteProductModal');
            $selProProposal.append($selSingleStrAdd);
            $selSingleStrAdd.find('.proSku').text($.trim($('#hiddenSkuz_' + id).val()));
            $selSingleStrAdd.find('.proName').text($.trim($('#hiddenNamez_' + id).val()));
            //注册图片放大方法
            $('div.imgOut').picZoom({
                imgWidth: '296',
                imgHeight: '296',
                divWidth: '300',
                divHeight: '300'
            });
            idProposals.push(id);
            if($('#editAndAdd').find(".tooltipHover[data-type='afterEdit']").length > 0){
                $selProProposal.find(".purSelSingle").addClass("imgHomeSm");
            }
            //添加产品数量处理
            if(add){
                $quoteProductModal.find('#selProProposalNum').html($('#selProProposal .purSelSingle').length);
            }else{
                $quoteProductModal.find('#selProProposalNum').html(idProposals.length);
            }
        },

        //弹层列表页全选
        chooseGoodsAllPage: function(supplierType) {
            var $chooseGoodsBtn;
            if(+supplierType === 1){ //判断是否从采购建议的多供货商全选
                $chooseGoodsBtn = $('.headTabPane[id="alreadyGhsProProduct"]').find('#SkusContent').find('.chooseGoodsBtn span');
            }else{
                $chooseGoodsBtn = $('#SkusContent').find('.chooseGoodsBtn span');
            }

            //备货建议-生成采购单
            if($('#hasSearchOverSeaPrepareDataID').val() === 'seaPrepare'){
                $chooseGoodsBtn = $('#quoteProductModal #SkusContent').find('.chooseGoodsBtn span');
            }

            $chooseGoodsBtn.each(function () {
                if ($.trim($(this).text()) === '选择') {
                    var $carryA = $(this).closest('a'),
                        goodsId = $carryA.attr('data-goodsId');
                    purProposal.selectProProposal(goodsId, $carryA , 'add');
                }
            })
        },

        //刪除已选
        delSelectTrProposal: function (pid,add) {
            var xbz = idProposals.indexOf(pid.toString()),
                $quoteProductModal = $('#quoteProductModal');
            if (+xbz !== -1) {
                var $selLi = $quoteProductModal.find('#selProProposal #selectDxmProductli_' + pid);
                if(+$selLi.attr('data-has') === 0) idProposalsOldDel.push(pid);
                idProposals.splice(xbz, 1);
                $selLi.remove();
            }

            if (add) {//添加产品数量处理
                $quoteProductModal.find('#selProProposalNum').html($('#selProProposal .purSelSingle').length);
            } else {
                $quoteProductModal.find("#selProProposalNum").html(idProposals.length);
            }
        },
        // 采购单的商品搜索
        btnProposalSelectSearchIt: function(){
            var $modal = $('#quoteProductModal'),
                searchSelectType = $modal.find('#searchProposalSelectType').val(),
                $searchValue = $modal.find('#searchProposalSelectValue'),
                searchValue = $.trim($searchValue.val());
            if (searchValue && (+searchSelectType === 1 || +searchSelectType === 3)) {
                MULTI_SEARCH.closeText(); //关闭已打开的多个搜索 textarea
                var val = searchValue.replace(/，/g,','),
                    skuCode = val.split(',');
                if(skuCode.length > 200){
                    var newContent = skuCode.slice(0, 200),
                        newStr = newContent.join(',');
                    $searchValue.val(newStr);
                    searchValue = newStr;
                }
            }
            var searchMode= 0;
            if ($('#searchDialogMode').length > 0) {
                searchMode = $('#searchDialogMode:visible').val();
            }else if ($('#searchMode').length > 0) {
                searchMode = $('#searchMode:visible').val();
            }

            searchValue = MYJ.escapeChar(searchValue, function(match, str){
                if (match === '\\') return '\\' + str;
            });

            $('#loading').modal('show');
            $.ajax({
                type: 'post',
                url: 'purchasingProposal/getProductsPageList.htm',
                data: {
                    searchSelectType: searchSelectType,
                    searchSelectValue: searchValue,
                    pageSize: $modal.find('#selectProposalPageList').find('#pageSize').val(),
                    selectIds : idProposals.join(),
                    fullCid: $('#catagoryHiddenId').val(),
                    searchMode: searchMode || 0
                    /*flag: 'alibaba'*/
                },
                dataType: "html",
                success: function(data){
                    $modal.find('#selectProposalPageList').html(data);
                    $('#loading').modal('hide');
                    $modal.customModal('hide');
                    $modal.customModal('show');
                }
            });
        },
        // 切换搜索条件
        setSelectGhsSearchType: function(type, obj){
            var $modal = $('#quoteProductModal'),
                selechValueStr = '';

            switch (+type) {
                case 1:
                    selechValueStr = '多个SKU间用逗号隔开';
                    break;
                case 3:
                    selechValueStr = '多个商品编码间用逗号隔开';
                    break;
                default:
                    selechValueStr = '';
                    break;
            }

            $modal.find("#searchGhsProposalSelectType").val(type);
            $modal.find("#searchGhsProposalSelectValue").attr("placeholder", selechValueStr);
            $(obj).closest("td").find(".tab-active").removeClass("tab-active");
            $(obj).addClass('tab-active');
            if (+type === 1){
                $('#ghsSearchMode').removeClass('myj-hide');
            } else{
                $('#ghsSearchMode').addClass('myj-hide');
            }
        },
        // 采购单的商品搜索
        btnProposalGhsSelectSearchIt: function(){
            var $modal = $('#quoteProductModal'),
                searchType = $modal.find('#searchGhsProposalSelectType').val().toString(),
                $searchValue = $modal.find('#searchGhsProposalSelectValue'),
                searchValue = $.trim($searchValue.val());

            if (searchValue && +searchType === 1) {
                MULTI_SEARCH.closeText(); //关闭已打开的多个搜索 textarea
                var temp = searchValue.replace(/，/g,','),
                    skuCode = temp.split(',');
                if(skuCode.length > 200){
                    var newContent = skuCode.slice(0, 200),
                        newStr = newContent.join(',');
                    $searchValue.val(newStr);
                    searchValue = newStr;
                }
            }
            $('#loading').modal('show');
            $.ajax({
                type: 'post',
                url: 'dxmSupplierProductRelation/getProductsForPurPropoalProRelPageList.htm',
                data: {
                    searchSelectType: searchType,
                    searchSelectValue: searchValue,
                    pageSize: $modal.find('#selectGhsProposalPageList').find('#pageSize').val(),
                    supplierId: $('#ghsProposalId').val(),
                    selectIds: idProposals.join(),
                    searchMode : $('#ghsSearchMode').val() || 0
                },
                dataType: 'html',
                success: function(data){
                    var isActiveAllGoods = $modal.find('.headTabNav > li.tab-check').attr('uid') === 'alreadyAllProProduct';

                    //找到对应节点显示列表数据
                    $modal.find('#' + (isActiveAllGoods ? 'selectProposalPageList' : 'selectGhsProposalPageList')).html(data);
                    purProposal.changeTabProposalSelectSku(isActiveAllGoods ? 'all' : 'ghs');
                    $('#loading').modal('hide');
                    $modal.customModal('hide');
                    $modal.customModal('show');
                }
            });
        },
        //切换 全部商品和供货商商品
        changeTabProposalSelectSku: function (bs) {
            var $modal = $('#quoteProductModal'),
                $allSearch = $modal.find('#cxtjProposalDivIdz'),//全部商品--搜索节点
                $searchType = $modal.find('#searchProposalSelectType'),//全部商品--搜索类型点
                $allSearchIpt = $modal.find('#searchProposalSelectValue'),//全部商品--输入框节点
                $allPageList = $modal.find('#alreadyAllProProduct'),//全部商品--列表节点
                $allPages = $modal.find('.proposalIdz'),//全部商品--分页节点
                $supplierSearch = $modal.find('#cxtjProposalGhsDivIdz'),//供货商商品--搜索节点
                $supplierSearchType = $modal.find('#searchProposalSelectType'),//供货商商品--输入框节点
                $supplierSearchIpt = $modal.find('#searchGhsProposalSelectValue'),//供货商商品--输入框节点
                $supplierPageList = $modal.find('#alreadyGhsProProduct'),//供货商商品--列表节点
                $supplierPages = $modal.find('.proposalGhsIdz'),//供货商商品--分页节点
                $headTabNav = $modal.find('.headTabNav'),
                isAllActive = bs === 'all',
                selechValueStr = '',
                searchType = isAllActive ? +$searchType.val() : +$supplierSearchType.val();

            $allSearch[isAllActive ? 'removeClass' : 'addClass']('myj-hide');
            $allPages[isAllActive ? 'removeClass' : 'addClass']('myj-hide');
            $allPageList[isAllActive ? 'removeClass' : 'addClass']('myj-hide');

            $supplierSearch[!isAllActive ? 'removeClass' : 'addClass']('myj-hide');
            $supplierPages[!isAllActive ? 'removeClass' : 'addClass']('myj-hide');
            $supplierPageList[!isAllActive ? 'removeClass' : 'addClass']('myj-hide');
            $headTabNav.find('li.borderBtmNo').removeClass('borderBtmNo');
            $headTabNav.find('li').eq(isAllActive ? 0 : 1).addClass('tab-check').siblings('li').removeClass('tab-check');
            switch (searchType) {
                case 1:
                    selechValueStr = '多个商品SKU间用逗号隔开，最多支持200个';
                    break;
                case 3:
                    selechValueStr = '多个商品编码间用逗号隔开，最多支持200个';
                    break;
                default:
                    selechValueStr = '';
                    break;
            }
            isAllActive ? $allSearchIpt.attr('placeholder', selechValueStr) : $supplierSearchIpt.attr('placeholder', selechValueStr);

            //先获取当前列表的所有选择的id
            var $pageListDiv = isAllActive ? $allPageList : $supplierPageList;

            $pageListDiv.find('.chooseGoodsBtn').each(function() {
                var $that = $(this);
                if(idProposals.indexOf($that.attr('data-goodsId')) !== -1){
                    $that.html('<span class="f-green">已选择</span>');
                }else{
                    $that.html('<span>选择</span>');
                }
            });

            MULTI_SEARCH.init(['商品SKU', '商品编码'], '', {
                boxClassName: '#changeTabProposalSearchBox'
            }); //初始化多个搜索 textarea
            MULTI_SEARCH.setPlaceholder('多个搜索请用回车换行(无需逗号结尾)，最多支持200个');
        },
        //添加商品确定
        addPurProposal: function (delId) {
            var $modal = $('#quoteProductModal'),
                $creatNoteModal = $('#createPurchasingNoteDiv'),
                divObj = $modal.find('#selProProposal').find('.purSelSingle'),
                uid = $creatNoteModal.find('.detailsModalTabChange').attr('uid'),
                tbodyObj = $creatNoteModal.find('#purchasingProposal_'+uid+' > tbody'),
                $creatModal = $('#createPurchasingNoteModal');

            $modal.find('#searchProposalSelectType').val('1');
            $modal.find('#searchProposalSelectValue').val('');

            idProposals = [];
            divObj.each(function(){
                var hasFlag = $(this).data('has');
                if (+hasFlag === 1) idProposals.push($(this).attr('id').split('_')[1]);
            });

            if(delId && delId.length){
                $.each(delId, function (i,j) {
                    $creatModal.find('#'+j).remove();
                })
            }
            if (idProposals.length) {
                $('#loading').modal('show');
                $.ajax({
                    type: 'post',
                    url: 'purchasingProposal/addDxmProduct.htm',
                    data: {
                        ids: idProposals.join()
                    },
                    dataType: 'html',
                    success: function (data) {
                        $('#loading').modal('hide');
                        $modal.customModal('hide');
                        tbodyObj.append(data);
                        var purInfo = $creatModal.find('.singlePlan[uid='+uid+'] .purchasingInfoBox');

                        if($('#hasSearchOverSeaPrepareDataID').val() === 'seaPrepare'){
                            CREATE_PURCHASE.showPurInfo(purInfo);
                        }else{
                            showPurInfo(purInfo);
                        }

                        $creatModal.modal('hide').modal('show');
                    }
                });
            }else{
                $modal.customModal('hide');
                var purInfo = $creatModal.find('.singlePlan[uid='+uid+'] .purchasingInfoBox');

                if($('#hasSearchOverSeaPrepareDataID').val() === 'seaPrepare'){
                    CREATE_PURCHASE.showPurInfo(purInfo);
                }else{
                    showPurInfo(purInfo);
                }
                $creatModal.modal('hide').modal('show');
            }
        },
        //在选择页面点击的确定，把选择的数据带过来
        addPurchasingProposal: function (obj) {
            var $selProProposal;
            if ($('#hasSearchOverSeaPrepareDataID').val() === 'seaPrepare') { //海外仓备货建议生成采购单
                $selProProposal = $('#quoteProductModal #selProProposal');
            } else {
                $selProProposal = $('#selProProposal');
            }

            if ($selProProposal.find(".purSelSingle").length == 0) {
                $.fn.message({type: 'error', msg: '请至少选择一个商品'});
                return;
            }
            var type = $(obj).attr('data-type');
            if (type === 'add') {
                whileAdd.addProduct();
            } else if(type === 'alibaba'){ //采购建议的1688采购建议
                alibabaPurchasingProposal.trueShowAddPurchasingProposal(idProposalsOldDel);
            }else if(type === 'shoudong'){ //手动采购创建、编辑，待到货创建
                var editOrAdd = $('#editOrAddFlag').val();
                if (editOrAdd == 'add') {
                    addOrEditDialog('');
                } else if (editOrAdd == 'edit') {
                    addOrEditDialog(this);
                }
            } else if (type === 'jihua'){ //采购计划
                $("#hiddenType").val('1');
                PURCHASEPLAN.trueShowAddPurchasePlan();
            }else{ //采购建议的备货、缺货建议
                purProposal.addPurProposal(idProposalsOldDel);
            }

            // 清空弹层上数据
            var $quoteProductModal = $('#quoteProductModal');
            $quoteProductModal.find('#selectProposalPageList').html('');
            $quoteProductModal.find('#selectGhsProposalPageList').html('');
        },

        //添加商品移除单个
        purSelDelSingle: function(obj) {
            var liId = $(obj).closest('.purSelSingle').attr('id').split('_')[1],
                $proContent = $('#alibabaSyncPurchasingBox').find('.proContent[data-proId="' + liId + '"]');

            if (!$proContent.length && +$proContent.attr('data-add')){//这里是1688同步采购单的添加商品弹层中做移除操作时的验证
                MYJ.message.error('该商品和当前订单产品已建立配对关系,无法移除');
                return;
            }
            $('#ida_' + liId).html('<span>选择</span>');
            $('.headTabPane[id="alreadyGhsProProduct"]').find('#ida_' + liId).html('<span>选择</span>');//采购建议-多供货商删除
            purProposal.delSelectTrProposal(liId);
        } ,

        //添加商品移除全部
        purSelDelAll: function(obj) {
            var $purSelSingle = $(obj).closest('.purSelBox').find('.purSelSingle'),
                liId = '',
                $proContent = '',
                count = 0;

            if ($purSelSingle.length){
                $.each($purSelSingle, function(i,j){
                    liId = $(j).attr('id').split('_')[1];
                    $proContent = $('#alibabaSyncPurchasingBox').find('.proContent[data-proId="'+liId+'"]');
                    if ($proContent.length && !+$proContent.attr('data-add')){//这里是1688同步采购单的添加商品弹层中做移除操作时的验证
                        count++;
                        return;
                    }
                    $('#ida_' + liId).html('<span>选择</span>');
                    $('.headTabPane[id="alreadyGhsProProduct"]').find('#ida_' + liId).html('<span>选择</span>');//采购建议-多供货商删除
                    purProposal.delSelectTrProposal(liId);
                });
                if (count) MYJ.message.error('有' + count + '个商品和当前订单产品已建立配对关系,无法移除');
            }
        },

        //获取分类树
        getTreeForCreateNoteAddPro: function () {
            var treeJson = '';
            $.ajax({
                type: 'post',
                url: 'purchasingProposal/getTreeForCreateNoteAddPro.json',
                data: 'json',
                async: false,
                success: function (_data) {
                    if(_data !== null) treeJson = _data;
                }
            });
            return treeJson;
        },
        //分类点击
        showCatagoryNameAdd: function(treeId,treeNode){
            $(this).closest('button').find('span[name="catagoryFullName"]').text(treeNode.name);
            $("#catagoryHiddenId").val(treeNode.fullCid);
            purProposal.btnProposalSelectSearchIt(); //分类点击搜索
        },
        //分页信息获取
        getPagingInfos: function() {
            var $modal = $('#quoteProductModal'),
                o = {};
            o.totalPages =  $modal.find('#totalPage').val() || 1; //总页码
            o.currentPage = $modal.find('#pageNo').val() || 1; //页码
            o.numberOfPages = $modal.find('#pageSize').val() || 30; //条数
            o.totalSize = $modal.find('#totalSize').val() || 1; //总条数
            o.numberOfPagesArr = [30,50,100]; //默认支持分页select切换的每页条数
            return o
        },
        //分页刷新全部商品采购计划页的添加商品
        quoteInitPage: function(options){
            var $modal = $('#quoteProductModal'),
                $pageList = $modal.find('#selectProposalPageList'),
                searchType = $modal.find('#searchProposalSelectType').val(),
                searchVal = $modal.find('#searchProposalSelectValue').val();
            if (searchVal && +searchType === 1) {
                var val = searchVal.replace(/，/g,','),
                    skuCode = val.split(',');
                if(skuCode.length > 200){
                    $.fn.message({type:'error',msg:'单次查询搜索只支持200个'});
                    return;
                }
            }
            var searchMode = 0 ;
            if ($('#searchDialogMode').length > 0) {
                searchMode = $('#searchDialogMode:visible').val();
            }else if ($('#searchMode').length > 0) {
                searchMode = $('#searchMode:visible').val();
            }
            $('#loading').modal('show');
            $.ajax({
                type: 'post',
                url: "purchasingProposal/getProductsPageList.htm",
                data: {
                    pageNo: options && options.pageNo ? options.pageNo : $('#pageNo').val() || 1,
                    pageSize: options && options.pageSize ? options.pageSize : $('#pageSize').val() || 50,
                    searchSelectType: searchType,
                    searchSelectValue: searchVal,
                    selectIds: idProposals.join(),
                    fullCid: $('#catagoryHiddenId').val(),
                    searchMode: searchMode || 0
                },
                dataType: 'html',
                success: function (data) {
                    $pageList.html(data);
                    $('#loading').modal('hide');
                    $modal.customModal('hide');
                    $modal.customModal('show');
                }
            });
            },
        //供货商列表页刷新
        quoteInitGhsPage: function(options){
            var $modal = $('#quoteProductModal'),
                $pageList = $modal.find('#selectGhsProposalPageList'),
                $upPage = $modal.find('#uPGhsProposalPageOpera'),
                $downPage = $modal.find('#downGhsProposalPageOpera'),
                searchType = $modal.find('#searchGhsProposalSelectType').val(),
                searchVal = $modal.find('#searchGhsProposalSelectValue').val(),
                ghsProposalId = $("#ghsProposalId").val();
            if (searchVal && +searchType === 1) {
                var temp = searchVal.replace(/，/g,','),
                    skuCode = temp.split(',');
                if(skuCode.length > 200){
                    $.fn.message({type:'error',msg:'单次查询搜索只支持200个'});
                    return;
                }
            }
            $('#loading').modal('show');
            $.ajax({
                type: 'post',
                url: "dxmSupplierProductRelation/getProductsForPurPropoalProRelPageList.htm",
                data: {
                    pageNo: options && options.pageNo ? options.pageNo : 1,
                    pageSize:options && options.pageSize ? options.pageSize : 50,
                    searchSelectType: searchType,
                    searchSelectValue: searchVal,
                    supplierId: ghsProposalId,
                    selectIds : idProposals.join(),
                    searchMode: $('#ghsSearchMode').val() || 0
                },
                dataType: 'html',
                success: function(data){
                    $pageList.html(data);
                    $('#loading').modal('hide');
                    $modal.customModal('hide');
                    $modal.customModal('show');
                }
            });
        },

        /*新版采购下单,需要用到已删除的产品id,和赋值选中的商品id*/
        //获取\清空已删除的产品id
        getDeleteProId : function (num) {
            if(num === 0){
                return idProposalsOldDel;
            }else{
                idProposalsOldDel = [];
            }
        },
        //把当前已选的商品id赋值给当前js文件中的idProposals数组,用来计算已选商品数量
        setIdProposals : function (arr) {
            idProposals = arr;
        },
        // 1688账号确定选择下单地址
        accountChangeAlibabaAddress: function (account, $selectAccountAlibaba, warehouseId) {
            if (account && warehouseId) {
                MYJ.ajax({
                    url: 'dxmPurchasingNote/getAlibabaAddressForWarehouseForProposal.json',
                    data: {
                        warehouseId: warehouseId,
                        alibabaId: account
                    },
                    success: function (data) {
                        if (+data.code === 0) {
                            purProposal.alibabaAddressRender(data.data, $selectAccountAlibaba);
                        } else {
                            $selectAccountAlibaba.find('#hiddenAddressInfo').attr('data-receive', '');
                            $selectAccountAlibaba.find('span.address').html('选择收货地址').attr('title', '');
                        }
                    }
                });
            } else {
                $selectAccountAlibaba.find('#hiddenAddressInfo').attr('data-receive', '');
                $selectAccountAlibaba.find('span.address').html('').attr('title', '');
            }
        },
        // 下单地址渲染
        alibabaAddressRender: function (data, $selectAccountAlibaba) {
            var str = '(' + data.fullName + '收)',
                townName = data.townName || '';
            if (data.mobilePhone) str += data.mobilePhone;
            if (data.phone) str += data.phone;
            str += data.addressCodeText + townName;
            str += data.address;
            $selectAccountAlibaba.find('#hiddenAddressInfo').attr('data-receive', data.id);
            $selectAccountAlibaba.find('#hiddenAddressInfo').attr('data-isaddressjoint', data.isAddressJoint);
            $selectAccountAlibaba.find('span.address').html(str).attr('title', str);
        },
        // 收货地址
        editAibabaAddress: function (obj) {
            $('#alibabaAddressListDiv').empty();
            var $currentTd = $(obj).closest('td'),
                authAlibabaId = $currentTd.find('#alibabaAccount').val(),
                addressId = $currentTd.find('#hiddenAddressInfo').attr('data-receive');
            if (!+authAlibabaId) {
                $.fn.message({type: 'error', msg: '请先选择账号'});
                 return;
            }
            $('#loading').modal('show');
            $.ajax({
                type: 'get',
                url: 'alibabaOrder/getAlibabaAddressList.htm?alibabaId=' + authAlibabaId + '&addressId=' + addressId,
                success: function (data) {
                    $('#loading').modal('hide');
                    $('#alibabaAddressListDiv').html(data);
                    $('#changeAlibabaAddressModal').find('.sureAddressBtn').attr('onclick', 'purProposal.sureChangeAlibabaAddress();');
                    $('#changeAlibabaAddressModal').modal('show');
                }
            });
        },
        // 同步收货地址
        asyncAlibabaAddress: function () {
            var alibabaId = $('.purchaseOrderSingle:not(:hidden)').find('.selectAlibabaAccount').val();
            if (!alibabaId) {
                $.fn.message({type: 'error', msg: '请选择1688账号'});
                return;
            }
            MYJ.ajax({
                url: 'alibabaOrder/asyncAlibabaAddressAgain.htm',
                pointKey: 'asyncAlibabaAddressAgain',
                data: {
                    alibabaId: alibabaId
                },
                success: function (res) {
                    $('#alibabaAddressListDiv').empty().html(res);

                    var asyncErrorCode = $('#asyncErrorCode').val();
                    if (asyncErrorCode !== '401') {
                        $.fn.message({type: 'success', msg: '同步成功'});
                    }
                    $('#changeAlibabaAddressModal').modal('show');
                }
            });
        },
        // 确定选择下单地址
        sureChangeAlibabaAddress: function () {
            var addressId = $('#alibabaAddressListDiv').find('input[name="alibabaAddress"]:checked').val(),
                $changeAlibabaAddressModal = $('#changeAlibabaAddressModal'),
                isAddressJoint = $changeAlibabaAddressModal.find('input.isAddressJoint').is(':checked');
            if (!addressId) {
                $.fn.message({type: 'error', msg: '请勾选一个地址!'});
                return;
            }
            $('#loading').modal('show');
            $.ajax({
                type: 'get',
                url: 'alibabaOrder/getAlibabaAddressById.json?addressId=' + addressId,
                success: function (data) {
                    $('#loading').modal('hide');
                    $changeAlibabaAddressModal.modal('hide');
                    data.isAddressJoint = isAddressJoint ? 1 : 0;
                    purProposal.alibabaAddressRender(data, $('.selAlibabaAdress'));
                    $changeAlibabaAddressModal.find('.sureAddressBtn').attr('onclick', 'PURCHASEPLAN.sureChangeAlibabaAddressForPlan();');
                }
            })
        }
    }
})(jQuery, document, window);

// 添加找货源
var initFindGoods = function (name, cancelType) {
    PURCHASE_SOURCE.initFindGoods(name, cancelType);
};
